/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
    vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
        vector<Interval> ret;
        Interval tmpInterval(newInterval.start, newInterval.end);
        bool hasMerge=false;
        for (int i=0;i<intervals.size();i++)
            if (hasMerge || intervals[i].end<tmpInterval.start || tmpInterval.end<intervals[i].start) {
                if (!hasMerge && tmpInterval.end<intervals[i].start) {
                    hasMerge=true;
                    ret.push_back(tmpInterval);
                }
                ret.push_back(intervals[i]);
            } else {
                tmpInterval.start=min(tmpInterval.start, intervals[i].start);
                tmpInterval.end=max(tmpInterval.end, intervals[i].end);
            }
        if (!hasMerge) ret.push_back(tmpInterval);
        return ret;
    }
};
